package com.itheima.prtice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;

@WebServlet("/co01")
public class CookServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需求：调用COOK方法获取最后的访问时间，并显示到浏览器
//        resp.setContentType("text/html;charset=utf-8");
//        resp.getWriter().print("获得的最后访问时间");
//        Cookie cookie = new Cookie("name", System.currentTimeMillis() + "");
//        resp.addCookie(cookie);
//        cookie.setMaxAge(3600);
//        Cookie[] cookies = req.getCookies();
//        for (Cookie cookie1 : cookies) {
//            if ("name".equals(cookie1.getName())) {
//                String value = cookie1.getValue();
//                SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd HH:dd:mm");
//                resp.getWriter().write(ddf.format(Long.parseLong(value)));
//            }
//        }
        //需求：调用COOK方法获取最后的访问时间，并显示到浏览器
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().print("最后一次访问cookies的时间：");
        //Long类型+""转换为字符串类型
        Cookie cookie=new Cookie("name",System.currentTimeMillis()+"");
        resp.addCookie(cookie);
        cookie.setMaxAge(-1);
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie1 : cookies) {
            if("name".equals(cookie1.getName())){
                String value = cookie1.getValue();
                resp.getWriter().write(value);//获得的是毫米值，需转换

            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
